<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Oversea_m extends CI_Model {
	function __construct()
    {
        parent::__construct();
    }
	
	public function savepurchasingNext()
	{
		$nosku = "";
		$sku = $this->input->post("sku");
		$seawarehouse =$this->input->post("seawarehouse");

		if(strstr($seawarehouse,'Amazon'))
		{
			$amz =1;	//发亚马迅
		}else{
			$amz = 0;	
		
		}



		
		if($sku=="")
		{
			return 201;
		}
		$strsku = explode("\n",$sku);
		if(is_array($strsku)){
			$strsku = array_filter(array_unique($strsku));	//去重去空数组
			foreach($strsku as $key=>$rs)
			{
				$where = " AND sku = '".trim($rs)."'";
				
				if($_COOKIE['ext_userid']  && $_COOKIE["ext_userid_open_goods"] ==0)
				{
					$ext_userID = $_COOKIE['ext_userid'];
					$where.=$where." AND oper in ($ext_userID)";
				}elseif($_COOKIE['ext_userid']  && $_COOKIE["ext_userid_open_goods"] ==1){
						$notext_userID = $_COOKIE['notext_userid'];
						if($notext_userID){
							$where.=$where." AND oper not in ($notext_userID)";
						}
				}else{
					if($_COOKIE["department"] != 1){
						$notext_userID = $_COOKIE['notext_userid'];
						if($notext_userID){
							$where.=$where." AND oper not in ($notext_userID)";
						}
					}
				}


				$rsdb=$this->fun->getdatabasesdetail('t_overseaproduct',$where);

				
				if($rsdb)
				{

					if($amz ==1)
					{

						$rsdb["stmemo"] ="";
						$rsdb["isst"] =0;	//保存
						$rsdb["ishw"] = 0;	//下一步不保存
						$rsdb["hwmemo"] = "";




					}else{
						if($rsdb["hw"]==1)
						{
							$rsdb["ishw"] = 0;	
							$rsdb["hwmemo"] = "";
						}else{
							$rsdb["hwmemo"] ="<br><font color=red>不在允许发往海外仓列表</font>";
							$rsdb["ishw"] =1;	//保存
						}
						$rsdb["stmemo"] ="";
						$rsdb["isst"] =0;	//保存
					
					}

					
					$list[]=$rsdb;
				}else{
					$nosku[]=$rs;
				}
			}
			
			if($list){
				
				if($nosku)
				{
					$strnosku= implode(",",$nosku);
				}
				return array("listdata"=>$list,"nosku"=>$strnosku);
			}else
			return 202;
		}
	}

	public function savepurchasing()
	{
		$seawarehouse =  $this->input->post('seawarehouse');
		$seawarehouseID = $this->fun->getdatabasesdetail('t_overseawarehouse'," AND name='".$seawarehouse."'",'id');
		$seawarehouseID = $seawarehouseID["id"];
		
		$starthouse =  $this->input->post('starthouse');
		$shopname     =  $this->input->post('shopname');
		$skunum       =  $this->input->post('skusum');
		$isst		  =  $this->input->post('isst');
		$ishw		  =  $this->input->post('ishw');

		$skuid		  =  $this->input->post('skuid');
		$goodsno	  =  $this->input->post('goodsno');
		$createUser	  =  $_COOKIE["username"];
		$uid		  =  $_COOKIE["userid"];
		$demandID		  =  $this->input->post('demand');	//销售申请需求列表ID
		
		
		/**************************************/
		if(is_array($skuid))
		{
			
			if($demandID)
			{
			
			}else{
				$rsdb = $this->db->get_one("SELECT * FROM t_oversea_demand WHERE 1 order by id DESC ");
				$tasknumber = trim($rsdb["demand_number"]);
				$nums = substr($tasknumber,8);
				if($nums)
				{
					$Number=$nums+1;
					$orderID = "TA".date("ymd").$Number;
				}else{
					$orderID = "TA".date("ymd")."1";
				}
				$post["demand_number"] = $orderID;
				$post["updatetime"] = date("Y-m-d");
				$post["status"] = 0;
				$post["create_id"] = $_COOKIE["userid"];
				$post["create_user"] = $_COOKIE["username"];
				$post["shopname"] = $shopname;
				$post["seawarehouse"] = $seawarehouse;
				$post["starthouse"] = $starthouse;
				$post["seaware_id"] = $seawarehouseID;
				$post["transportation"]=$this->input->post('transportmode');
				$post["skucount"] = count($skuid);
				$post["nums"] = array_sum($skunum);

				$this->db->insert("t_oversea_demand",$post);
				$demandID = $this->db->insert_id();
			}
			
			$allcosprice = 0;
			foreach($skuid as $key=>$rs)
			{
				/*
				$rsdb = $this->db->get_one("SELECT * FROM t_overseapurchasing WHERE status = 0 and createUID = '".$uid."' AND seaware_id = '".$seawarehouseID."' AND oversearproduct_id='".$rs."' and ");
				if($rsdb)
				{
					$sql = "UPDATE t_overseapurchasing SET";
					$sql.=" skunum=skunum+'".$skunum[$key]."'";
				}else{
				
					$sql = "INSERT INTO t_overseapurchasing SET";
					$sql.=" skunum='".$skunum[$key]."'";
				}*/

				$sql = "INSERT INTO t_overseapurchasing SET";
				$sql.=" skunum='".$skunum[$key]."'";
				$sql.=",seawarehouse='".$seawarehouse."'";
				$sql.=",demandID='".$demandID."'";
				$sql.=",seaware_id='".$seawarehouseID."'";
				$sql.=",shopname='".$shopname."'";
				$sql.=",goodsno='".strtoupper($goodsno[$key])."'";
				$sql.=",oversearproduct_id='".$rs."'";
				$sql.=",remark='".$remark[$key]."'";
				$sql.=",createUser='".$createUser."'";
				$sql.=",createUID='".$uid."'";
				$sql.=",opertime='".date("Y-m-d H:i:s")."'";
				//算成本价
				$cosprice = $this->fun->get_Goods_costprice(strtoupper($goodsno[$key]));
				$allcosprice = $allcosprice +$cosprice*$skunum[$key];
				if($rsdb)
				{
					//$sql.= " WHERE id='".$rsdb["id"]."'";
				}
				if(($isst[$key]==0 || $ishw[$key]==0) && $skunum[$key]>0)
				{
					$this->db->update("t_oversea_demand",array("costprice"=>$allcosprice),"id=".$demandID);
					$this->db->query($sql);
				}
			}
		}
	

	
	
	}

	function delpurlist()
	{
        $ppid=$this->input->post('ppid');
        if(count($ppid)>0){
            $del_ids=implode(',',$ppid);

			 $this->db->query("DELETE FROM t_oversea_demand WHERE id in(".$del_ids.") and status = 0");
            $this->db->query("DELETE FROM t_overseapurchasing WHERE demandID in(".$del_ids.") and status = 0");
             $history_url=$_SERVER['HTTP_REFERER'];
            echo "<script language='javascript'>location.href='$history_url';</script>";   
        }else{
            $id = $this->input->post('id');
            $this->db->query("DELETE FROM t_overseapurchasing WHERE id = '".$id."'");
			 $demandID = $this->input->post('demandID');
			//重新计算库存数
			$this->m->getoverseapurchasingdata($demandID);
        }
	}
	function getoverseapurchasingdata($addgoodsorderID)
	{
		$listskucount = $this->fun->getdatabasesdetail("t_overseapurchasing"," AND demandID = '".$addgoodsorderID."'","count(id) as skucount");
		$counts = $listskucount["skucount"];
		$sums = $allcosprice= 0;
		$list = $this->db->get_where("t_overseapurchasing"," demandID = '".$addgoodsorderID."'")->result_array();
		foreach($list as $key=>$sd)
		{
			$sums = $sums+$sd["skunum"];
			//算成本价
			$cosprice = $this->fun->get_Goods_costprice($sd["goodsno"]);
			$allcosprice = $allcosprice +$cosprice*$sd["skunum"];
		}
		$this->db->query("UPDATE t_oversea_demand SET skucount = $counts,nums='".$sums."',costprice='".$allcosprice."' where id = '".$addgoodsorderID."'");
	}
	function delproduct()
	{
		$id = $this->input->post('id');
		$this->db->query("DELETE FROM t_overseaproduct WHERE id = '".$id."'");
	}
	function delstatuslist()
	{
		$id = $this->input->post('id');
		$this->db->query("DELETE FROM t_transport_status WHERE id = '".$id."'");
	}
	
	function delwarehouse()
	{
		$id = $this->input->post('id');
		$this->db->query("DELETE FROM t_overseawarehouse WHERE id = '".$id."'");
	}
	function getsku()
	{
		$rsdb = $this->fun->getdatabasesdetail('t_overseaproduct'," AND sku='".trim($this->input->post('sku'))."'");
		return $rsdb;
	}
	function saveproduct()
	{
		$id = intval($this->input->post('id'));
		if($id)
		{
			$sql="UPDATE t_overseaproduct SET ";
			$rsdb = $this->fun->getdatabasesdetail('t_overseaproduct'," AND id='".$id."'");
		}else{
			$sql="INSERT INTO t_overseaproduct SET ";
		}
		$sql.=" sku='".trim($this->input->post('sku'))."'";
		$sql.=" ,name='".trim($this->input->post('name'))."'";
		$sql.=" ,costprice='".trim($this->input->post('costprice'))."'";
		$sql.=" ,weight='".trim($this->input->post('weight'))."'";
		$sql.=" ,volumenum='".trim($this->input->post('volumenum'))."'";
		$sql.=" ,lengthnum='".trim($this->input->post('lengthnum'))."'";
		$sql.=" ,widthnum='".trim($this->input->post('widthnum'))."'";
		$sql.=" ,heightnum='".trim($this->input->post('heightnum'))."'";

		
		if($id)
		{
			$sql.=" WHERE id ='".$id."' ";
			$this->db->query($sql);
			
			//如果长宽高与之前不一样，重新计算头程
			if($rs['lengthnum'] != trim($this->input->post('lengthnum')) || $rs['widthnum'] != trim($this->input->post('widthnum'))  || $rs['heightnum'] != trim($this->input->post('heightnum'))  )
			{
				//重新计算头程
				$this->fun->again_oversea_express_costprice(trim($this->input->post('sku')));

			}


		}else{
			$sql.=" ,opertime='".date("Y-m-d H:i:s")."'";
			$sql.=" ,opername='".$_COOKIE["username"]."'";
			$sql.=" ,oper='".$_COOKIE["userid"]."'";
			$this->db->query($sql);
			$id = $this->db->insert_id();
		}
		
		return $id;
	}
	function savewarehouse()
	{
		$id = $this->input->post('id');
		if($id)
		{
			$sql="UPDATE t_overseawarehouse SET ";
		}else{
			$sql="INSERT INTO t_overseawarehouse SET ";
		}
		$sql.=" name='".trim(addslashes($this->input->post('name')))."'";
		$sql.=" ,country='".trim($this->input->post('country'))."'";
		$sql.=" ,code='".trim($this->input->post('code'))."'";
		$sql.=" ,address='".trim(addslashes($this->input->post('address')))."'";
		$sql.=" ,city='".trim($this->input->post('city'))."'";
		$sql.=" ,province='".trim($this->input->post('province'))."'";
		$sql.=" ,zipcode='".trim($this->input->post('zipcode'))."'";
		$sql.=" ,contactperson='".trim($this->input->post('contactperson'))."'";
		$sql.=" ,tel='".trim($this->input->post('tel'))."'";
		$sql.=" ,worktime='".trim($this->input->post('worktime'))."'";

		
		if($id)
		{
			$sql.=" WHERE id ='".$id."' ";
			$this->db->query($sql);
			
		}else{
			$sql.=" ,opertime='".date("Y-m-d H:i:s")."'";
			$sql.=" ,opername='".$_COOKIE["username"]."'";
			$this->db->query($sql);
			$id = $this->db->insert_id();
		}
		
		return $id;
	}
	function getpurchprolist()
	{
		//先查询目前仓库中有多少SKU是需要发货
		$ts = 0;
		$endhouse = $this->input->post('endhouse');
		$shopname = $this->input->post('shopname');
		if(trim($this->config->item('destination')))
		{
			$destination = trim($this->config->item('destination'));
			if(strstr($endhouse,$destination))
			{
				$ts =1;
				$where = " AND shopname='".$shopname."'";
			}
		}
		$query = $this->db->query("Select oversearproduct_id,goodsno,seaware_id,shopname,B.name,B.weight,B.costprice,B.lengthnum,B.widthnum,B.heightnum,B.volumenum,B.st from t_overseapurchasing A left join t_overseaproduct B on A.oversearproduct_id = B.id WHERE A.status = 0 AND seawarehouse='".$endhouse."' $where group by oversearproduct_id ");
        $dates = $query->result_array();
		foreach($dates as $key=>$rs)
		{
			if($ts ==1)
			{
				$sqls="AND shopname='".$rs["shopname"]."' AND seaware_id='".$rs["seaware_id"]."'";
			}else{
				$sqls="AND seaware_id='".$rs["seaware_id"]."'";
			}
			$where = " and status=0 and oversearproduct_id = '".$rs["oversearproduct_id"]."' $sqls";
		
			$list = $this->fun->getdatabaseslist('t_overseapurchasing',$where,'skunum,createUser,id,goodsno,remark');
			$dates[$key]["goodslist"] = $list;
			$res = $this->db->get_one("SELECT SUM(skunum)  AS totalnum FROM t_overseapurchasing WHERE 1 $where");
			$dates[$key]["totalnum"] = $res["totalnum"];
			
		}
		return $dates;
	}
	function getpacking()
	{
		
		$competenceID = $this->input->post('competenceID');	//选择好需要发货的SKU ID
		$realsend = $this->input->post('realsend');			//填写的发货数量
		$overseapurchasing = $this->input->post('overseapurchasing');	//对应的ID号
		$fnsku = $this->input->post('fnsku');	//fNSKU
		$oversearproduct = $this->input->post('oversearproduct_id');	//SKU_ID
		if(is_array($competenceID))
		{
			foreach($competenceID as $key=>$rs)
			{
				$newrealsend[]= $realsend[$rs];	//获取选择需要本次发货的数量
				$newoverseapurchasing[]= $overseapurchasing[$rs]; //获取选择需要本次发货的ID
			}
		}
		
		foreach($newoverseapurchasing as $key=>$overseapurchasing_ID)	//循环获得ID
		{
			$nums = $newrealsend[$key];
			foreach($overseapurchasing_ID as $se=>$res)
			{
				$id =  $res;	//t_overseapurchasing 库中的ID
				$numsts =  $nums[$se];	//t_overseapurchasing 库中实际计划发货数量
				if($numsts>0){
				$where = " AND A.id = '".$id."'";
				$list = $this->fun->getdatabasesdetail('t_overseapurchasing A left join t_overseaproduct B on A.oversearproduct_id=B.id',$where," A.id as pid,A.skunum,A.createUser,A.opertime,A.shopname,A.seawarehouse,B.sku,B.costprice");
				$list["sendnums"] = $numsts;
				$detail[] =$list;	//详细需要发货的列表
				}
				
			}
		}
		foreach($competenceID as $key=>$rs)
		{
			$skuid = $this->fun->getdatabasesdetail("t_overseapurchasing"," AND id ='".$rs."'");
			$where = " AND id = '".$skuid["oversearproduct_id"]."'";
			$goods= $this->fun->getdatabasesdetail('t_overseaproduct',$where," id,sku,name,weight,costprice,lengthnum,widthnum,heightnum,volumenum,st ");

			foreach($realsend[$rs] as $s=>$f)
			{
				$numst = $numst+$f;
			}
			$goods["sendnums"] = $numst;
			$goods["st"] = $goods['st'];
			$goods["totalprice"] = $numst * $goods["costprice"];
			$goods["fnsku"] = $fnsku[$rs][0];
			$numst = 0;
			$goodslist[] =$goods;
		}
		return array("goodslist"=>$goodslist,"detail"=>$detail);
	}
	
	function savefile()
	{
		$tpid = $this->input->post('tpid');
		$upload_path = 'uploads/oversea/'.date("Ymd")."/";
		$dir = dirname(__FILE__) . "/../../".$upload_path;
		!is_dir($dir) && @mkdir($dir, 0755, true);
		$this->db->trans_begin();
		$msg = $this->fun->uploadfile($upload_path,$tpid,'oversea',1);

		if($msg["st"] == 200)
		{
			$filename = $msg["filename"];
			$nums = count($filename);
			for($i=1;$i<=$nums;$i++)
			{
				$imgdata = "";
				$imgdata["tpid"] = $tpid;
				$imgdata["images_url"] = $msg["filename"][$i][0];
				$imgdata["local_url"] = $msg["filename"][$i][2];
				$imgdata["filename"] = $msg["filename"][$i][0];
				$imgdata["filesize"] = $msg["filename"][$i][1];
				$imgdata["createUser"] = $_COOKIE["username"];
				$imgdata["instime"] = time();
				if($msg["filename"][$i][0]!=3000003)
				{
					$this->db->query($this->db->insert_string('t_oversea_file', $imgdata));
				}
			}

			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
			}
			else
			{
				$this->db->trans_commit();
			}
		}
		return $msg;
	}
	function saveOverseaRules()
	{
		if($this->input->post('orderstatus'))
		{
			$orderstatus  =implode(",",$this->input->post('orderstatus'));
		}
		$postdata= "";
		$postdata["name"]    = trim($this->input->post('name'));
		$postdata["country"] = trim($this->input->post('country'));
		$postdata["countryflag"] = trim($this->input->post('countryflag'));
		$postdata["shopname"] = trim($this->input->post('shopname'));
		$postdata["shopflag"] = trim($this->input->post('shopflag'));
		$postdata["goodsnoflag"] = trim($this->input->post('goodsnoflag'));
		$postdata["goodsno"] = trim($this->input->post('goodsno'));
		$postdata["weight1"] = trim($this->input->post('weight1'));
		$postdata["weight2"] = trim($this->input->post('weight2'));
		$postdata["amount1"] = trim($this->input->post('amount1'));
		$postdata["amount2"] = trim($this->input->post('amount2'));
		$postdata["freight1"] = trim($this->input->post('freight1'));
		$postdata["freight2"] = trim($this->input->post('freight2'));
		$postdata["costprice1"] = trim($this->input->post('costprice1'));
		$postdata['costprice2'] = trim($this->input->post('costprice2'));
		$postdata['length1'] = trim($this->input->post('length1'));
		$postdata['length2'] = trim($this->input->post('length2'));
		$postdata['width1'] = trim($this->input->post('width1'));
		$postdata['width2'] = trim($this->input->post('width2'));
		$postdata['heigth1'] = trim($this->input->post('heigth1'));
		$postdata['heigth2'] = trim($this->input->post('heigth2'));
		$postdata['calcvalue1'] = trim($this->input->post('calcvalue1'));
		$postdata['calcvalue2'] = trim($this->input->post('calcvalue2'));
		$postdata['sumvalue1'] = trim($this->input->post('sumvalue1'));
		$postdata['sumvalue2'] = trim($this->input->post('sumvalue2'));
		$postdata['zipcode'] = trim($this->input->post('zipcode'));
		$postdata['zipcodeflag'] = trim($this->input->post('zipcodeflag'));
		$postdata['street'] = trim($this->input->post('street'));

		$postdata['stockstatus'] = trim($this->input->post('stockstatus'));

		$postdata["orderstatus"] = $orderstatus;

		$postdata["logistics"]  =trim($this->input->post('logisticsName'));


		$postdata['deliveroversea'] = trim($this->input->post('deliveroversea'));
		$postdata['transportoversea'] = trim($this->input->post('transportoversea'));


		$postdata["priority"] = trim($this->input->post('priority'));
		$postdata["opertime"] = date("Y-m-d H:i:s");
		$postdata["oper"] = $_COOKIE["username"];
		$this->db->trans_begin();

		if($this->input->post("id"))
		{
			$this->db->update("db_oversea_rules",$postdata,"id=".$this->input->post("id"));
			$intid =intval($this->input->post("id"));
		}else{
			$this->db->insert("db_oversea_rules",$postdata);
			$intid = $this->db->insert_id();
		}


		$sql = "";
		if($postdata["country"])	//国家Sql
		{
			$country = explode(";",$postdata["country"]);
			$country = implode("','",$country );
			if($this->input->post("countryflag")==1)
				$sql.= " AND country_cn not in ('".$country."')";
			else
				$sql.= " AND country_cn in ('".$country."')";
		}
		if($postdata["shopname"])	//店铺SQL
		{
			$shopname = explode(";",$postdata["shopname"]);
			$shopname = implode("','",$shopname );
			if($this->input->post("shopflag")==1)
				$sql.= " AND shopname not in ('".$shopname."')";
			else
				$sql.= " AND shopname in ('".$shopname."')";
		}

		if($postdata["zipcode"])	//邮编SQL
		{
			$zipcode = explode(";",$postdata["zipcode"]);
			$zipcode = implode("','",$zipcode );
			if($this->input->post("zipcodeflag")==1)
				$sql.= " AND zipcode not in ('".$zipcode."')";
			else
				$sql.= " AND zipcode in ('".$zipcode."')";
		}

		if($postdata["street"])	//收货人街道包含指定字符  SQL
		{
			$street = explode(";",$postdata["street"]);
			$str_conn = "";
			foreach($street as $k=>$v){
				$str_conn.= " address like '%$v%' or address2 like '%$v%' or";
			}
			$str_conn = trim($str_conn,"or");
			$sql.= " AND ( $str_conn ) ";
		}
		if($postdata["logistics"]){ //ebay 买家选择的配送方式
			$logistics= explode(";",$postdata["logistics"]);
			$logistics = implode("','",$logistics );
			$sql.= " AND postageservice in ('".$logistics."')";

		}
		if($postdata["freight1"])	//运费SQL
		{
			$sql.= " AND shipping_fee >= $postdata[freight1] ";
		}
		if($postdata["freight2"]){
			$sql.=" AND shipping_fee <= $postdata[freight2] ";
		}

		if($postdata["amount1"])	//订单总金额  商品金额+运费
		{
			$sql.= " AND goods_amount+shipping_fee >= $postdata[amount1] ";
		}
		if($postdata['amount2']){
			$sql.=" AND goods_amount+shipping_fee <= $postdata[amount2] ";
		}

		if($postdata["weight1"])	//订单重量
		{
			$sql.= " AND orderweight >= {$postdata['weight1']}  ";
		}
		if($postdata["weight2"]){
			$sql.=" AND orderweight <= {$postdata['weight2']} ";
		}

		/**该项判断有问题
		if($postdata["goodsno"])	//商品编号SQL
		{
			$goodsno = explode(";",$postdata["goodsno"]);
			$goodsno = implode("','",$goodsno );
			if($this->input->post("goodsnoflag")==1)
				$sql.= " and order_id in(select distinct order_id from db_order_sell where goods_sn not in ('".$goodsno."'))";
			else
				$sql.= " and order_id in(select distinct order_id from db_order_sell where goods_sn  in ('".$goodsno."'))";
		}**/

		//长宽高 成本等判断条件

		if($orderstatus)	//订单状态SQL
		{
			$sql.= " and order_status in($orderstatus)";
		}
		if($sql)
		{
			$this->db->update("db_oversea_rules",array("sqlfilter"=>$sql),"id=".$intid);
		}

		if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
			return false;
		}
		else
		{
			$this->db->trans_commit();
		}

		return true;
	}
	function savedelivery()
	{
		
		//如果有上传文件，先把文件 上传
		 $picname = $_FILES['upfiles']['name'];
		 if ($picname != "") {
            $type = strtolower(strstr($picname,'.'));
			
            if ($type != ".zip" && $type != ".rar" && $type != ".pdf") {
                echo '格式不对！只允许 上传.zip .rar .pdf';
                exit;
            }
            $rand = rand(100, 999);
            $pics = date("YmdHis") . $rand . $type;
            //上传路径
            $file = dirname(__FILE__) . "/../../uploads/";
            $file2 = date("Ymd");

            $this->fun->mkdirpath($file . $file2);
            $pic_path = $file . $file2 . "/" . $pics;
            move_uploaded_file($_FILES['upfiles']['tmp_name'], $pic_path);
			$filename  ="/uploads/".$file2 . "/" . $pics;
        }
		$planid = $this->input->post('transportationplanning_id'); //修改ID
		if($planid)
		{
			$rsdb = $this->db->get_one("SELECT * FROM t_transportationplanning WHERE id = '".$planid."'");
		
			$detail= unserialize($this->input->post('detail'));
			$seawarehouse =$detail[0]["seawarehouse"];
			if(strstr($seawarehouse,'Amazon'))
			{
				if($filename && $rsdb["status"] ==7)
				{
					$wet=",status=1";
				}
			}
			
			$gooddata = $this->input->post('goodslist');
			foreach($detail as $key=>$rs)
			{
				if($rs["sku"] == $gooddata["sku"][$key])
				{
					$detail[$key]["sendnums"] = $gooddata["sendnums"][$key];
				}
				
			}


			
			if($gooddata){
				//重新计划成本与数量
			$goodslist= serialize($this->input->post('goodslist'));
			$detail= serialize($detail);
			
			foreach($gooddata["sendnums"] as $ky=>$rd)
			{
				$numst = $numst+$rd;
				$price = $gooddata["costprice"][$ky] * $rd;
				$totalprice=$totalprice+$price;
			}
			$carrier		 = $this->input->post('carrier');
			if($filename)
			{
				$wet.=",upfiles='".$filename."'";
			}
		
			/*
			$this->db->query("update t_transportationplanning SET transportmode='".$this->input->post('transportmode')."',goodslist='".$goodslist."',totalnum='".$numst."',carrier='".$carrier."',totalamount='".$totalprice."'$wet,detaillist='".$detail."' where id ='".$planid."'");
				if($filename){	//上传了PDF才需要审核
				//设置系统Message提醒 一审
					if($this->config->item('firsttrial') && $this->config->item('overseatipopen')==1)
					{
							$randid = $this->message->getMessageNums();	//获取当前存储的条数	
							$firsttrial = explode("|",$this->config->item('firsttrial'));
							$orderID = $this->input->post('groupid');
							foreach($firsttrial as $rs)
							{
								$postMessageData["message_type"] = $this->message->getMessageType(2);	//申请库存
								$postMessageData["message"] =$_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."提交了运输计划 {$orderID}，等待一审";
								$postMessageData["message_toName"] = $rs;
								$postMessageData["url"] = '/oversea/deliveryplanlist';
								$postMessageData["isread"] =  $randid;
								$this->fun->saveMessage($postMessageData);
							}
					}
				}*/

			}
			return $planid;
		}

		


		$shopname		 = $this->input->post('shopname');
		$carrier		 = $this->input->post('carrier');
		$transportmode	 = $this->input->post('transportmode');
		$starthouse		 = $this->input->post('starthouse');
		$endhouse		 = $this->input->post('endhouse');
		$goodslist		 = serialize($this->input->post('goodslist'));
		$detail			 = $this->input->post('detail');
		$projectdate	 = $this->input->post('projectdate');
		
			//自动生成申请编号
		$rsdb = $this->db->get_one("SELECT * FROM t_transportationplanning WHERE 1 order by id DESC ");
		$tasknumber = trim($rsdb["groupid"]);
		$nums = substr($tasknumber,8);
		if($nums)
		{
			$Number=$nums+1;
			$orderID = "TP".date("ymd").$Number;
		}

		$status = $this->input->post('status')?$this->input->post('status'):1;
		$sql = "INSERT INTO t_transportationplanning SET";
		$sql.=" groupid = '".$orderID."'";
		$sql.=" ,shopname = '".$shopname."'";
		$sql.=" ,projectdate = '".$projectdate."'";
		$sql.=" ,status = '3'";
		$sql.=" ,startingplace = '".$starthouse."'";
		$sql.=" ,destination = '".$endhouse."'";
		$sql.=" ,carrier = '".$this->input->post('carrier')."'";
		$sql.=" ,transportmode = '".$this->input->post('transportmode')."'";
		$sql.=" ,skunum = '".$this->input->post('totalsku')."'";

		$sql.=" ,totalnum = '".$this->input->post('totalnum')."'";
		$sql.=" ,totalamount = '".$this->input->post('totalprice')."'";
		$sql.=" ,totalmoney = '".$this->input->post('totalmoney')."'";
		$sql.=" ,createoper = '".$_COOKIE["username"]."'";
		$sql.=" ,createtime = '".date("Y-m-d H:i:s")."'";
		$sql.=" ,goodslist = '".$goodslist."'";
		$sql.=" ,detaillist = '".$detail."'";
		$sql.=" ,upfiles = '".$filename."'";
		
		
		$this->db->query($sql);
		$id = $this->db->insert_id();

		$detail= unserialize($this->input->post('detail'));
		foreach($detail as $key=>$detailrs)
		{
			$allsendnums=0;
			$sendnums = $detailrs["sendnums"];
			$rsbing = $this->db->get_one("SELECT * FROM t_overseapurchasing WHERE id = '".$detailrs["pid"]."'  AND goodsno='".$detailrs["sku"]."'");
			$allsendnums = $rsbing["sendnums"]+$sendnums;
			$sqls ="";
			if($allsendnums >=$rsbing["skunum"])
			{
				$sqls="status = 1 ,";	
			}
			$this->db->query(" UPDATE t_overseapurchasing SET $sqls sendnums=sendnums+$sendnums,verifyNums=verifyNums-$sendnums  where id='".$detailrs["pid"]."'");	//保存发货进行审核前就标识信息已经处理
			$demandID = $rsbing["demandID"];

		}

		//判断demandID 是否都已经发完了，如果发完了，则申请调拨单改为完成
		if($demandID){
			$rsbing = $this->db->get_one("SELECT * FROM t_overseapurchasing WHERE demandID = '".$demandID."' AND status=0");
			if(!$rsbing)
			{
				$this->db->update("t_oversea_demand",array("status"=>5),"id=".$demandID);
			}
			//将TP ID保存在列表中
			$this->db->query(" UPDATE t_oversea_demand SET planning_id=concat_ws('|',planning_id,'".$id."')  where id='".$demandID."'");
		}


	
		if($filename){	//上传了PDF才需要审核

			//这里不需要再一审核了 2018-01-09
		//设置系统Message提醒 一审
			/*
			if($this->config->item('firsttrial') && $this->config->item('overseatipopen')==1)
			{
					$randid = $this->message->getMessageNums();	//获取当前存储的条数	
					$firsttrial = explode("|",$this->config->item('firsttrial'));
					foreach($firsttrial as $rs)
					{
						$postMessageData["message_type"] = $this->message->getMessageType(2);	//申请库存
						$postMessageData["message"] =$_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."提交了运输计划 {$orderID}，等待一审";
						$postMessageData["message_toName"] = $rs;
						$postMessageData["url"] = '/oversea/deliveryplanlist';
						$postMessageData["isread"] =  $randid;
						$this->fun->saveMessage($postMessageData);
					}
			}*/
		}
		return $id;

	}
	function saveoverseapurchasingstatus()
	{
		
		$sql = "SELECT id,demandID,`status`,skunum,sendnums,skunum-sendnums AS topnums  FROM t_overseapurchasing HAVING topnums <=0 AND demandID >0 and `status` = 0";
		$query = $this->db->query($sql);
        $dates = $query->result_array();
		foreach($dates as $key=>$rs)
		{
			$this->db->update("t_overseapurchasing",array("status"=>1),"id=".$rs["id"]);
		}

		$sql = "SELECT * from t_oversea_demand where id not in(SELECT demandID from t_overseapurchasing where 1 and  demandID >0 AND `status` = 0 ) and `status` !=4 and `status` !=5";
		$query = $this->db->query($sql);
        $dates = $query->result_array();
		foreach($dates as $key=>$rs)
		{
			$this->db->update("t_oversea_demand",array("status"=>5),"id=".$rs["id"]);
		}
	}
	function getboxnumber()
	{
		$rsdb = $this->db->get_one("SELECT count(id) as nums FROM t_transportbox WHERE 1 ");
		$Number=$rsdb["nums"]+1;
		$boxID = date("ymd").$Number.rand(10,100);
		return $boxID;
	}
	
	function savecompare()
	{
		$groupid = $this->input->post('groupid');
		$planid = $this->input->post('transportationplanning_id');
		$nowbuynum = $this->input->post('nowbuynum');
		$id = $this->input->post('id');
		$container = $this->input->post('container');
		$cartons = $this->input->post('cartons');
		$weight	=$this->input->post('weight');
		$costprice	=$this->input->post('costprice');

		
		$skunum = 0;
		$quantity = 0;
		foreach($nowbuynum as $rs)
		{
			$quantity=$quantity+$rs;
			if($rs>0)$skunum = $skunum+1;
		}
		foreach($nowbuynum as $key=>$rs)
		{
			if($rs>0)
			{
				$prices = $rs*$costprice[$key];
				$allprice = $allprice+$prices;	//箱子成本
			}
		}
		
		
		if($this->config->item('cartons')){	
		 $cartonslist = explode("\r\n",$this->config->item('cartons'));
		 $cartonscostlist = explode("\r\n",$this->config->item('cartonscost'));
		 foreach($cartonslist as $key=>$rs)
		  {
			if($rs == $cartons)
			 {
			   $onecartonscost =  $cartonscostlist[$key];
			 }
		 }
		}
		
		//$skunum = count($id);
		
		$boxnumber = $_POST['boxnumber']."-".trim($_POST["box"]);	//箱号
	
		
		$sql = " INSERT INTO  t_transportbox SET";
		$sql.="  planid ='".$planid."'";
		$sql.=" ,groupid ='".$groupid."'";
		$sql.=" ,boxnumber ='".$boxnumber."'";
		$sql.=" ,sku ='".$skunum."'";
		$sql.=" ,quantity ='".$quantity."'";
		$sql.=" ,weight ='".$weight."'";
		$sql.=" ,specifications ='".$cartons."'";
		$sql.=" ,allprice ='".$allprice."'";
		if($onecartonscost)
			$sql.=",cartonscost='".$onecartonscost."'";
		$sql.=" ,createname ='".$_COOKIE["username"]."'";
		$sql.=" ,createtime ='".date("Y-m-d H:i:s")."'";

	
		$this->db->query($sql);
		$insertid = $this->db->insert_id();
		
		
		//存发货状态
		foreach($id as $key=>$rs)
		{
			$atcnum = $nowbuynum[$key];
			if($atcnum){
				$res = $this->fun->getdatabasesdetail('t_overseapurchasing'," AND id='".$rs."'");
				$this->db->query(" INSERT INTO  t_transportlist SET  ist =0,groupid = '".$groupid."' ,planid ='".$planid."',boxnumber ='".$boxnumber."',transportbox_id='".$insertid."',pid='".$rs."',nowbuynum='".$atcnum."',cartons='".$cartons."',weight='".$weight."',sku='".$res["goodsno"]."',skuid='".$res["oversearproduct_id"]."'"); //存明细列表
			    $this->db->query(" UPDATE t_overseapurchasing SET actualdelivery=actualdelivery+$atcnum where id='".$rs."'");	//更新用户需求表
			}
		}
		//处理有凑箱的情况
		$TDid = $this->input->post('TDid');
		$TDnowbuynum = $this->input->post('TDnowbuynum');
		$TDcostprice=$this->input->post('TDcostprice');
		foreach($TDnowbuynum as $key=>$rs)
		{
			if($rs>0)
			{
				$prices = $rs*$TDcostprice[$key];
				$TDallprice = $TDallprice+$prices;	//箱子成本
			}
		}
		foreach($TDid as $key=>$rs)
		{
			$atcnum = $TDnowbuynum[$key];
			if($atcnum){
				$res = $this->fun->getdatabasesdetail('t_overseapurchasing'," AND id='".$rs."'");
				$this->db->query(" INSERT INTO  t_transportlist SET ist =1,groupid = '".$groupid."' ,planid ='".$planid."',boxnumber ='".$boxnumber."',transportbox_id='".$insertid."',pid='".$rs."',nowbuynum='".$atcnum."',cartons='".$cartons."',weight='".$weight."',sku='".$res["goodsno"]."',skuid='".$res["oversearproduct_id"]."'"); //存明细列表
			    $this->db->query(" UPDATE t_overseapurchasing SET actualdelivery=actualdelivery+$atcnum where id='".$rs."'");	//更新用户需求表
				//核算成本


				$this->db->query(" UPDATE t_transportbox SET quantity=quantity+$atcnum,allprice=allprice+$TDallprice where id='".$insertid."'");	//更新箱子数量
			}
		}

		return $planid;

	}

	/*
	function savecompare()
	{
		$groupid = $this->input->post('groupid');
		$planid = $this->input->post('transportationplanning_id');
		$nowbuynum = $this->input->post('nowbuynum');
		$id = $this->input->post('id');
		$container = $this->input->post('container');
		$cartons = $this->input->post('cartons');
		$weight	=$this->input->post('weight');
		$costprice	=$this->input->post('costprice');
		
		$quantity = 0;
		foreach($nowbuynum as $rs)
		{
			$quantity=$quantity+$rs;
		}
		foreach($nowbuynum as $key=>$rs)
		{
			if($rs>0)
			{
				$prices = $rs*$costprice[$key];
				$allprice = $allprice+$prices;	//箱子成本
			}
		}
		
		//还需要存耗材价格
		
		if($this->config->item('cartons')){	
		 $cartonslist = explode("\r\n",$this->config->item('cartons'));
		 $cartonscostlist = explode("\r\n",$this->config->item('cartonscost'));
		 foreach($cartonslist as $key=>$rs)
		  {
			if($rs == $cartons)
			 {
			   $onecartonscost =  $cartonscostlist[$key];
			 }
		 }
		}
		

		$boxnumber = $groupid."-".trim($_POST["box"]);	//箱号
		$sql = " INSERT INTO  t_transportbox SET";
		$sql.="  planid ='".$planid."'";
		$sql.=" ,groupid ='".$groupid."'";
		$sql.=" ,boxnumber ='".$boxnumber."'";
		$sql.=" ,quantity ='".$quantity."'";
		$sql.=" ,weight ='".$weight."'";
		$sql.=" ,specifications ='".$cartons."'";
		$sql.=" ,allprice ='".$allprice."'";
		if($onecartonscost)
			$sql.=",cartonscost='".$onecartonscost."'";
		$sql.=" ,createname ='".$_COOKIE["username"]."'";
		$sql.=" ,createtime ='".date("Y-m-d H:i:s")."'";
		$this->db->query($sql);
		$insertid = $this->db->insert_id();
		
		
		//存发货状态
		foreach($id as $key=>$rs)
		{
			$atcnum = $nowbuynum[$key];
			if($atcnum){
				$res = $this->fun->getdatabasesdetail('t_overseapurchasing'," AND id='".$rs."'");
				$this->db->query(" INSERT INTO  t_transportlist SET  ist =0,groupid = '".$groupid."' ,planid ='".$planid."',boxnumber ='".$boxnumber."',transportbox_id='".$insertid."',pid='".$rs."',nowbuynum='".$atcnum."',cartons='".$cartons."',weight='".$weight."',sku='".$res["goodsno"]."',skuid='".$res["oversearproduct_id"]."'"); //存明细列表
			    $this->db->query(" UPDATE t_overseapurchasing SET status = 1 ,actualdelivery=actualdelivery+$atcnum where id='".$rs."'");	//更新用户需求表
			}
		}

		
		//处理有凑箱的情况
		$TDid = $this->input->post('TDid');
		$TDnowbuynum = $this->input->post('TDnowbuynum');
		foreach($TDid as $key=>$rs)
		{
			$atcnum = $TDnowbuynum[$key];
			if($atcnum){

				$res = $this->fun->getdatabasesdetail('t_overseapurchasing'," AND id='".$rs."'");
				$this->db->query(" INSERT INTO  t_transportlist SET ist =1,groupid = '".$groupid."' ,planid ='".$planid."',boxnumber ='".$boxnumber."',transportbox_id='".$insertid."',pid='".$rs."',nowbuynum='".$atcnum."',cartons='".$cartons."',weight='".$weight."',sku='".$res["goodsno"]."',skuid='".$res["oversearproduct_id"]."'"); //存明细列表
			    $this->db->query(" UPDATE t_overseapurchasing SET status = 1 ,actualdelivery=actualdelivery+$atcnum where id='".$rs."'");	//更新用户需求表

				//重新计算总数和成本
				$ressku = $this->fun->getdatabasesdetail('t_overseaproduct'," AND sku='".$res["goodsno"]."'");
				$price = $ressku["costprice"];
				$allprice = $price * $atcnum;
				$this->db->query(" UPDATE t_transportationplanning SET totalnum =totalnum+$atcnum ,totalamount=totalamount+$allprice where id='".$planid."'");	//凑箱的情况下更新总表
				$this->db->query(" UPDATE t_transportbox SET quantity =quantity+$atcnum,allprice =allprice+$allprice where id='".$insertid."'");	//凑箱情况下更新箱子数量
				
			}
		}

		return $planid;

	}
	*/

	function changstatus()
	{
		$id = $this->input->post('id');
		$t = $this->input->post('t');
		$type =  $this->input->post('type');
		$back_message = trim($this->input->post('back_message'));
		if($type==1)
		{
			if($t>=4)
			{
				
				//如果是取消计划，需要将调拨数量返回
				$rsdb = $this->db->get_one("SELECT detaillist,status,startingplace FROM t_transportationplanning WHERE id='".$id."'");
				if($t==6)
				{
					
					$detaillist= unserialize($rsdb["detaillist"]);
					foreach($detaillist as $key=>$rs)
					{
						$sendnums = $rs["sendnums"];//已发数量
						$this->db->query("UPDATE t_overseapurchasing SET status='0',sendnums=sendnums-$sendnums,verifyNums=verifyNums+$sendnums where id='".$rs["pid"]."'");
						$rsbing = $this->db->get_one("SELECT * FROM t_overseapurchasing WHERE id = '".$rs["pid"]."'");
						$demandID = $rsbing["demandID"];
					}
					if($demandID){
						$this->db->update("t_oversea_demand",array("status"=>3),"id=".$demandID);
					}
				}
				if($t==8)	//取消完成
				{
					$this->db->query("UPDATE t_transportationplanning SET status=3 where id='".$id."'");
				}else{
					$this->db->query("UPDATE t_transportationplanning SET status='".$t."' where id='".$id."'");
				}
				
				
			
			}else{
				$this->db->query("UPDATE t_oversea_demand SET status='".$t."' where id='".$id."'");
			}
			
			if($back_message && $t==0)	//退回到新创建
			{
				$randid = $this->message->getMessageNums();	//获取当前存储的条数,一审人员和申请人
				$firsttrial = explode("|",$this->config->item('firsttrial'));
				$rsdb = $this->db->get_one("SELECT * FROM t_oversea_demand WHERE id='".$id."'");
				array_push($firsttrial,$rsdb['create_user']);
				foreach($firsttrial as $rs)
				{
					$postMessageData["message_type"] = $this->message->getMessageType(0);	//新创建
					$message= $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."计划{$rsdb[groupid]}退回新创建,原因 {$back_message}";
					$postMessageData["message"] = $message;
					$postMessageData["message_toName"] = $rs;
					$postMessageData["url"] = '/oversea/demandList?id='.$id;
					$postMessageData["isread"] =  $randid;
					$this->fun->saveMessage($postMessageData);
				}
			}


			if($t == 2)	//一审通过
			{
				//设置系统Message提醒 二审
				if($this->config->item('secondtrial') && $this->config->item('overseatipopen')==1)
				{
						$randid = $this->message->getMessageNums();	//获取当前存储的条数	
						$secondtrial = explode("|",$this->config->item('secondtrial'));
						foreach($secondtrial as $rs)
						{
							$rsdb = $this->db->get_one("SELECT * FROM t_oversea_demand WHERE id='".$id."'");
							$postMessageData["message_type"] = $this->message->getMessageType(3);	//二审
							$message						 = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."审核通过了运输计划 {$rsdb[demand_number]}，等待二审";
							$postMessageData["message"] = $message;
							$postMessageData["message_toName"] = $rs;
							$postMessageData["url"] = '/oversea/showplandetail/'.$id;
							$postMessageData["isread"] =  $randid;
							$this->fun->saveMessage($postMessageData);
						}
				}
			}

			if($t == 3)	//二审通过
			{
				//设置系统Message提醒 二审
				if($this->config->item('packingman') && $this->config->item('overseatipopen')==1)
				{
						$randid = $this->message->getMessageNums();	//获取当前存储的条数	
						$packingman = explode("|",$this->config->item('packingman'));
						foreach($packingman as $rs)
						{
							$rsdb = $this->db->get_one("SELECT * FROM t_oversea_demand WHERE id='".$id."'");
							$postMessageData["message_type"] = $this->message->getMessageType(4);	//二审
							$message						 = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."审核通过了运输计划 {$rsdb[demand_number]}，等待封箱";
							$postMessageData["message"] = $message;
							$postMessageData["message_toName"] = $rs;
							$postMessageData["url"] = '/oversea/deliveryplanlist?other='.$rsdb['demand_number'];
							$postMessageData["isread"] =  $randid;
							$this->fun->saveMessage($postMessageData);
						}
				}
			}

			return $id;
		}else{

			$this->db->trans_begin();

			//预防重复提交 更新库存
			$sql_task = "SELECT * FROM  t_transportationtask WHERE 1 AND id='".$id."'";
			$rs_task  = $this->db->query($sql_task)->row_array();
			if($rs_task["status"] == $t)
			{
				return $id;
			}
			
		

			//运输任务完成时，需要设置箱子运输状态，如果所有箱子都是完成状态，则将运输计划也设定为完成即t_transportationplanning status 5
		$this->db->query("UPDATE t_transportationtask SET status='".$t."' where id='".$id."'");
		$this->db->query("UPDATE t_transportbox SET transport_st=1 where task_id='".$id."'");	//标注所有的TT的箱子运输完成！

		if($t==5&&$type==2){
			//如果是亚马逊仓，需要记录入库时间，作为库息计算基础
			$rsShop = $this->fun->getdatabasesdetail('d_shop'," AND name = '".$rs_task['shopname']."'");
			if($rsShop['platfrom'] == 2)
			{
				$goodslist = $this->fun->getdatabaseslist('t_transportlist'," AND tasknumber = '".$rs_task['tasknumber']."'");
				if(count($goodslist)>0)
				{
					foreach($goodslist as $key=>$rs)
					{
						$cotnet =trim($rs['tasknumber'])."-FBA入库";
						$goods = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku = '".$rs['sku']."'");
						$oldnum = $this->fun->getdatabasesdetail('db_fba_stock'," AND sku = '".$rs['sku']."' AND shopid='".$rsShop['id']."' AND Warehouse_code='SELLABLE' ");
						if(!$oldnum['Quantity'])
						{
							$oldnum['Quantity'] = 0;
						}
						$newnum = $oldnum['Quantity'] + $rs['nowbuynum'];
						$this->fun->goods_stock_log($id,$goods['goods_id'],$rsShop['id'],$cotnet,$rs['nowbuynum'],1,$oldnum['Quantity'],$newnum,'',1); 
					}
				}

			}

			

			//确认完成的时候，更新相关库存
			$oversea_startId = trim($this->input->post('oversea_startId'));
			$oversea_destinationId = trim($this->input->post("oversea_destinationId"));
			$arr_oversea_orgin = array(3,4,6,9); //海外仓仓库id
			//$arr_oversea = array(3,5,6,7); //正式仓库
			$arr_sku = $this->input->post();
			//始发地 目的地仓库 start    || in_array($oversea_startId,$arr_oversea_orgin) 不用减库存
			if(in_array($oversea_destinationId,$arr_oversea_orgin)){
				foreach($arr_sku as $key=>$value){
					if($key=="op" || $key=="t" || $key=="id" || $key=="type" || $key == "oversea_startId" || $key == "oversea_destinationId"){
						continue;
					}
					$sql = "SELECT * FROM db_goods WHERE goods_sku = '{$key}' ";
					$rs  = $this->db->query($sql)->row_array();;
					if(count($rs)>0){
						//海外运输 目的地仓库
						if(in_array($oversea_destinationId,$arr_oversea_orgin)){
							if($oversea_destinationId==3){
								$storage_id = 6; //EZGO美国仓
								$storage_name = "美国仓";
							}
							if($oversea_destinationId==4){
								$storage_id = 3; //英华英国仓
								$storage_name = "英国仓";
							}
							if($oversea_destinationId==6){
								$storage_id = 5; //英华德国仓
								$storage_name = "德国仓";
							}
							if($oversea_destinationId==9){
								$storage_id = 7; //万邑通美西仓
								$storage_name = "美西仓";
							}
							$sql_stock = "SELECT * FROM db_goods_stock WHERE goods_id = {$rs['goods_id']} AND storage_id = {$storage_id} ";
							$rs_stock  = $this->db->query($sql_stock)->row_array();
							if(count($rs_stock)>0){
								$stock_num = $rs_stock['stock']+$value;
								$this->db->update("db_goods_stock",array('stock'=>$stock_num)," goods_id = '{$rs['goods_id']}' AND storage_id = '{$storage_id}' ");

								//更新商品表日志
								$goodslog="";
								$goodslog["goods_id"] = $rs['goods_id'];	//更新商品表 日志信息
								$goodslog["updatetime"] = date("Y-m-d H:i:s");
								$goodslog["createUid"] = $_COOKIE['userid'];
								$goodslog["types"] = 2; //库存信息
								$goodslog["content"] = $storage_name.",更新商品库存[{$stock_num}],原库存[{$rs_stock['stock']}],商品sku=".$rs['goods_sku'];
								$goodslog["createUser"] =$_COOKIE['username'];
								$this->db->insert('db_goods_log', $goodslog);

							}else{
								//插入库存
								$arr_goods_stock = array();
								$arr_goods_stock['goods_id'] = $rs['goods_id'];
								$arr_goods_stock['storage_id'] = $storage_id;
								$arr_goods_stock['storage_name'] = $storage_name;
								$arr_goods_stock['stock'] = $value;
								$arr_goods_stock['in_transit'] = 0;
								$arr_goods_stock['waitday'] = 0;
								$this->db->insert('db_goods_stock',$arr_goods_stock);

								//更新商品表日志
								$goodslog="";
								$goodslog["goods_id"] = $rs['goods_id'];	//更新商品表 日志信息
								$goodslog["updatetime"] = date("Y-m-d H:i:s");
								$goodslog["createUid"] = $_COOKIE['userid'];
								$goodslog["types"] = 2; //库存信息
								$goodslog["content"] = $storage_name.",增加商品库存[{$value}],商品sku=".$rs['goods_sku'];
								$goodslog["createUser"] =$_COOKIE['username'];
								$this->db->insert('db_goods_log', $goodslog);

							}
						}

						//存日志
						//$this->fun->goods_stock_log($rs['id'],$detail['goods_id'],0,$cotnet,$goods_num,0,$oldnum,$newnum);    //库存日志

						//海外运输 始发地仓库
						/**
						if(in_array($oversea_startId,$arr_oversea_orgin)){
							if($oversea_startId==3){
								$storage_id = 6; //EZGO美国仓
								$storage_name = "EZGO美国仓";
							}
							if($oversea_startId==4){
								$storage_id = 3; //英华英国仓
								$storage_name = "英华英国仓";
							}
							if($oversea_startId==6){
								$storage_id = 5; //英华德国仓
								$storage_name = "英华德国仓";
							}
							if($oversea_startId==9){
								$storage_id = 7; //万邑通美西仓
								$storage_name = "万邑通美西仓";
							}
							$sql_stock = "SELECT * FROM db_goods_stock WHERE goods_id = {$rs['goods_id']} AND storage_id = {$storage_id} ";
							$rs_stock  = $this->db->query($sql_stock)->row_array();
							if(count($rs_stock)>0){
								$stock_num = $rs_stock['stock']-$value;
								$this->db->update("db_goods_stock",array('stock'=>$stock_num)," goods_id = '{$rs['goods_id']}' AND storage_id = '{$storage_id}' ");

								//更新商品表日志
								$goodslog="";
								$goodslog["goods_id"] = $rs['goods_id'];	//更新商品表 日志信息
								$goodslog["updatetime"] = date("Y-m-d H:i:s");
								$goodslog["createUid"] = $_COOKIE['userid'];
								$goodslog["types"] = 2; //库存信息
								$goodslog["content"] = $storage_name.",更新商品库存[{$stock_num}],原库存[{$rs_stock['stock']}],商品sku=".$rs['goods_sku'];
								$goodslog["createUser"] =$_COOKIE['username'];
								$this->db->insert('db_goods_log', $goodslog);
							}else{
								//理论上不会进入该流程
							}
						}**/
					}
				}
			}//始发地 目的地仓库 end

		}

		//查找运输任务某完成的
		$sql = "SELECT DISTINCT(planid) FROM `t_transportbox` A left join t_transportationplanning B on A.planid = B.id WHERE 1 AND transport_st=1 AND B.status !=5";
		$query = $this->db->query($sql);
        $dates = $query->result_array();
		foreach($dates as $key=>$rs)
		{
			$planid = $rs["planid"];
			$res = $this->db->get_one("SELECT * FROM t_transportbox WHERE planid='".$planid."' and transport_st =0");
			if($res)
			{
			
			}else{
				//说明全部运输完成，将运输计划标成完成
				$this->db->query("UPDATE t_transportationplanning SET status=5 where id='".$planid."'");
			
			}
		}
			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
			}
			else
			{
				$this->db->trans_commit();
			}

		return $id;
		}

	}
	function deldelitt()
	{
		$id = $this->input->post('id');
		$res = $this->fun->getdatabasesdetail('t_transportationplanning'," AND id='".$id."'");
		$detaillist= unserialize($res["detaillist"]);
		foreach($detaillist as $key=>$rs)
		{
			$this->db->query("UPDATE t_overseapurchasing SET status='0' where id='".$rs["pid"]."'");
		}

		$this->db->query("DELETE FROM  t_transportationplanning where id='".$id."'");
		return $id;

	}
	function deltask()
	{
		$id = $this->input->post('id');
		$this->db->query("UPDATE t_transportbox SET boxstatus='0',tasknumber='',task_id='' where task_id='".$id."'");
		$this->db->query("UPDATE t_transportlist SET taskid='',tasknumber='' where taskid='".$id."'");
		$this->db->query("DELETE FROM  t_transportationtask where id='".$id."'");
	}
	public function getboxtypelistlist($database,$where,$page =1,$if_csv=0,$pageSize=100,$orderbys='')
    {
		if(!$orderbys)
		{
			$orderbys = " order by id desc";
		}
		$sql = "SELECT A.id as pid,A.*,B.* FROM  $database WHERE 1";
		
		$sql.=$where;
		
		if ($page != null) {
			$offset = ($page - 1) * $pageSize;
			$limit = " LIMIT $pageSize OFFSET $offset";
		}
		$wheresql = $sql.$orderbys.$limit;
        $query = $this->db->query($wheresql);
        $dates = $query->result_array();

		$sqlCount = $sql;
        $query2 = $this->db->query($sqlCount);
        $allCount = $query2->num_rows();
	  return array('list' => $dates, 'total' => $allCount);
    }

	function savetxtypedetail()
	{
		
		
		$id = $this->input->post('transportationplanning_id');
		$starthouse = $this->input->post('starthouse');
		$destination = $this->input->post('endhouse');
		//$projectdate = trim($this->input->post('projectdate'));
		$endprojectdate = $this->input->post('endprojectdate');
		$cargostatus = $this->input->post('cargostatus');
		$boxnumberID = $this->input->post('boxnumberID');
		$carrier = $this->input->post('carrier');
		$beiprojectdate = $this->input->post('beiprojectdate');
		$tasknumber = $this->input->post('orderID');
		$shopname = $this->input->post('shopname');
		
		if($boxnumberID)
		{
			$boxnumberIDlist = implode(",",$boxnumberID);
		}

			//$freight = serialize($this->input->post('freight'));
		//$projectdateremake = serialize($this->input->post('projectdateremake'));
		
		//查询箱子的SKU数量
		$quantity = $this->input->post('quantity');
		foreach($quantity as $key=>$rs)
		{
			$totalnum = $totalnum+$rs;
		}
		$allprice = $this->input->post('allprice');
		foreach($allprice as $key=>$rs)
		{
			$totalamount = $totalamount+$rs;
		}
		$cartonscost = $this->input->post('cartonscost');	//箱子成本
		foreach($cartonscost as $key=>$rs)
		{
			$cartonscostprice = $cartonscostprice+$rs;
		}
		$skunum = $this->input->post('skunum');
		foreach($skunum as $key=>$rs)
		{
			$skunumT = $skunumT+$rs;
		}
		
		$rsdb = $this->db->get_one("SELECT * FROM t_transportationtask WHERE tasknumber='".trim($tasknumber)."' ");
		if($rsdb)
		{
			echo "运输任务编号存在！请返回重新选择箱子！";
			die;
		}
		$statuss = $this->fun->getdatabasesdetail("t_transportationplanning"," AND id='".$id."'","status");
		if($statuss["status"]==4)
		{
			$this->db->query("UPDATE t_transportationplanning SET status='8' where id='".$id."'");
		}

		//自动保存发货任务
		$sql=" INSERT INTO t_transportationtask SET";
		$sql.=" tasknumber='".$tasknumber."'";
		$sql.=" ,shopname='".$shopname."'";
		$sql.=" ,carrier='".$carrier."'";
		$sql.=" ,beiprojectdate='".$beiprojectdate."'";
		$sql.=" ,status=1";
		$sql.=" ,startingplace='".$starthouse."'";
		$sql.=" ,destination='".$destination."'";
		$sql.=" ,skunum='".$skunumT."'";
		$sql.=" ,totalnum='".$totalnum."'";
		$sql.=" ,totalamount='".$totalamount."'";
		$sql.=" ,totalmoney='".$cartonscostprice."'";
		$sql.=" ,createoper='".$_COOKIE["username"]."'";
		$sql.=" ,createtime='".date("Y-m-d H:i:s")."'";
		
		$this->db->trans_begin();
		$this->db->query($sql);
		$id = $this->db->insert_id();

		foreach($boxnumberID as $key=>$rs)
		{
			$this->db->query("UPDATE t_transportbox SET boxstatus='1',tasknumber='".$tasknumber."',task_id='".$id."' where id='".$rs."'");
			$this->db->query("UPDATE t_transportlist SET taskid='".$id."',tasknumber='".$tasknumber."' where transportbox_id='".$rs."'");
		}
		//生成TT,需要对商品进行减库存操作
		$this->Reduceinventory($boxnumberIDlist,$tasknumber);

		if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
		}
		else
		{
			$this->db->trans_commit();
		}
		
		return $id;
	}

	function savefuyi()
	{
		
		$rsdb = $this->db->get_one("SELECT * FROM t_transport_status WHERE task_id='".trim($this->input->post("ClentID"))."' ");
		if(!$rsdb)
		{
	       $this->db->query("UPDATE t_transportationtask SET projectdate='".trim($this->input->post("projectdate"))."',status = 2 where id='".$this->input->post("ClentID")."'");
		}

		if($this->input->post("statusid"))
		{
			$sql.= "UPDATE  t_transport_status set carrier='".trim($this->input->post("carrier"))."' ,weight='".trim($this->input->post("weight"))."' ,transportmode='".trim($this->input->post("transportmode"))."', projectdate='".trim($this->input->post("projectdate"))."', endprojectdate='".trim($this->input->post("endprojectdate"))."',freight='".trim($this->input->post("freight"))."',delivery_fee='".trim($this->input->post("delivery_fee"))."',clearance_fee='".trim($this->input->post("clearance_fee"))."',tariffs_fee='".trim($this->input->post("tariffs_fee"))."',other_fee='".trim($this->input->post("other_fee"))."',projectdateremake='".trim($this->input->post("projectdateremake"))."',ck='".trim($this->input->post("ck"))."',cargostatus='".trim($this->input->post("cargostatus"))."',instime	='".date("Y-m-d H:i:s")."',createUser='".$_COOKIE["username"]."' where id='".$this->input->post("statusid")."'";
			$this->db->query($sql);
		}else{
			$sql.= "INSERT INTO t_transport_status set task_id='".trim($this->input->post("ClentID"))."',weight='".trim($this->input->post("weight"))."' ,carrier='".trim($this->input->post("carrier"))."' ,transportmode='".trim($this->input->post("transportmode"))."', projectdate='".trim($this->input->post("projectdate"))."', endprojectdate='".trim($this->input->post("endprojectdate"))."',freight='".trim($this->input->post("freight"))."',delivery_fee='".trim($this->input->post("delivery_fee"))."',clearance_fee='".trim($this->input->post("clearance_fee"))."',tariffs_fee='".trim($this->input->post("tariffs_fee"))."',other_fee='".trim($this->input->post("other_fee"))."',projectdateremake='".trim($this->input->post("projectdateremake"))."',ck='".trim($this->input->post("ck"))."',cargostatus='".trim($this->input->post("cargostatus"))."',instime	='".date("Y-m-d H:i:s")."',createUser='".$_COOKIE["username"]."'";
			$this->db->query($sql);
		}
		$tasklist = $this->db->get_where('t_transportationtask','id='.$this->input->post("ClentID"))->result_array();
		if($tasklist[0]["projectdate"]==''||$tasklist[0]["projectdate"]=='0000-00-00')
		{
			$rsdbst = $this->db->get_one("SELECT * FROM t_transport_status WHERE task_id='".trim($this->input->post("ClentID"))."' order by id ASC ");
			if($rsdbst["projectdate"]){
			 $this->db->query("UPDATE t_transportationtask SET projectdate='".trim($rsdbst["projectdate"])."' where id='".$this->input->post("ClentID")."'");
			}
		}
		
		//预估运费
		$rsdb = $this->db->get_one("select * from t_transportationtask where  id='".$this->input->post("ClentID")."'");
		$rsdbnew = $this->db->get_one("select(SUM(freight)+SUM(delivery_fee)+SUM(clearance_fee)+SUM(tariffs_fee)+SUM(other_fee)) as allfreigth  FROM t_transport_status where task_id = '".trim($this->input->post("ClentID"))."'");
		if($rsdbnew["allfreigth"])
		{
			 $this->db->query("UPDATE t_transportationtask SET freight='".$rsdbnew["allfreigth"]."'  where id='".$this->input->post("ClentID")."'");
		}

	}

	function getreport($where,$page =1,$if_csv=0,$pageSize=100,$orderbys='')
	{
	
		$orderbys1  = "group by A.`skuid` DESC";
		$orderbys = $orderbys1.$orderbys;
		$sql = "SELECT A.*,B.*,C.costprice,sum( A.nowbuynum ) AS amount_num,count(*) AS task_num FROM  t_transportlist A LEFT JOIN t_transportationtask B ON A.taskid = B.id LEFT JOIN t_overseaproduct C ON A.skuid=C.id WHERE A.taskid>0 ";

		
		$sql.=$where;
		
	

		if ($page != null) {
			$offset = ($page - 1) * $pageSize;
			$limit = " LIMIT $pageSize OFFSET $offset";
		}
		$wheresql = $sql.$orderbys.$limit;
		
        $query = $this->db->query($wheresql);
        $dates = $query->result_array();

		$sqlCount = $sql.$orderbys;
        $query2 = $this->db->query($sqlCount);
        $allCount = $query2->num_rows();
		$alldates = $query2->result_array();
	  return array('list' => $dates, 'total' => $allCount,'alldates'=>$alldates);
	}

	function savestockgrn($types)
	{
		//自动生成申请编号
		if($types==1)
		{
			$sin= "SI";
			$where = " AND types = 1";
		}else{
			$sin = "SO";
			$where = " AND types = 2";
		}
		$rsdb = $this->db->get_one("SELECT * FROM t_overseastock_grn WHERE 1 $where order by id DESC ");
		
		$tasknumber = trim($rsdb["orderno"]);
		
		$nums = substr($tasknumber,8);
		if($nums)
		{
			$Number=$nums+1;
			$orderID = $sin.date("ymd").$Number;
		}else{
			$orderID = $sin.date("ymd")."1";
		}
		
		$postdata['orderno']  = $orderID;
		$postdata['is_check']	= 0;
		$postdata['types'] =$types;
		$postdata['createUid']  = $_COOKIE["userid"];
		$postdata['updatetime']	=date("Y-m-d H:i:s");
		$this->db->query($this->db->insert_string('t_overseastock_grn', $postdata));
		$parentID = $this->db->insert_id();
		return $orderID;
	}

	function savestockgoods($sku,$nums,$orderID)
	{
		if(count($sku)>0)
		{
			
			foreach($sku as $key=>$rs)
			{
				$postdata = "";
				$postdata['orderno']  = $orderID;
				$postdata['sku']	= trim($rs);
				$postdata['stock'] =$nums[$key];
				$this->db->query($this->db->insert_string('t_overseastock_goods', $postdata));
				$parentID = $this->db->insert_id();
			}
		}
		return true;
	}

	function yz()
	{
		if($_REQUEST["yz"]==1)
		{
			$yz = 0;
		}else{
			$yz = 1;
		}
		$sql = "UPDATE t_overseawarehouse SET yz = $yz where id = '".$this->input->get('id')."'";
		$this->db->query($sql);
	}

	function hw()
	{
		if($_REQUEST["yz"]==1)
		{
			$yz = 0;
		}else{
			$yz = 1;
		}
		$sql = "UPDATE t_overseaproduct SET hw = $yz where id = '".$this->input->get('id')."'";
		$this->db->query($sql);
	}


	function st()
	{
		if($_REQUEST["yz"]==1)
		{
			$yz = 0;
		}else{
			$yz = 1;
		}
		$sql = "UPDATE t_overseaproduct SET st = $yz where id = '".$this->input->get('id')."'";
		$this->db->query($sql);
	}
	
	function getpaixu()
	{
		$paixu = trim($_POST["paixu"]);
		$sql = "UPDATE t_overseawarehouse SET paixu = $paixu where id = '".$this->input->post('id')."'";

		$this->db->query($sql);
	}

	function Reduceinventory($id,$tasknumber)
	{
		$storage_id = 0;
		$cotnet = "封箱出库";
		$list =$this->db->select('groupid,nowbuynum,sku,id')->get_where("t_transportlist","transportbox_id in($id)")->result_array();
		$task = $this->fun->getdatabasesdetail('t_transportationtask'," AND tasknumber='".$tasknumber."'");
		if($task["startingplace"] =='2号仓库 (C2)' || $task["startingplace"]=='1号仓库 (C1)')	//减1号仓库存
		{
			$storage_id = 1; 
			$storage_name = "一号仓";
		}

		if($task["startingplace"] =='英华英国仓 (E2)')	//减英国仓库存
		{
			$storage_id = 3; 
			$storage_name = "英国仓";
		}

		if($task["startingplace"] =='英华德国仓 (D2)')	
		{
			$storage_id = 5; 
			$storage_name = "德国仓";
		}
		if($task["startingplace"] =='万邑通美西仓 (USWC)')	
		{
			$storage_id = 7; 
			$storage_name = "美西仓";
		}
		if($task["startingplace"] =='EZGO美国仓 (U2)')
		{
			$storage_id = 6; 
			$storage_name = "美国仓";
		}
		if($storage_id==0)
		{
			return;
		}

		foreach($list as $key=>$rs)
		{
			$groupid = $rs["groupid"];

			$detail = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".$rs['sku']."'");
			if($detail)
			{
			$goods_num = -$rs["nowbuynum"];

			
			$sql_stock = "SELECT * FROM db_goods_stock WHERE goods_id = '{$detail['goods_id']}' AND storage_id = {$storage_id} "; //默认入库一号仓
			$rs_stock  = $this->db->query($sql_stock)->row_array();
			if($rs_stock['stock']<0){
				$rs_stock['stock'] = 0;
			}

			$this->fun->savestock($detail['goods_id'],$storage_name,$goods_num,0);
			//存日志
			$oldnum = $rs_stock['stock']?$rs_stock['stock']:0;
			$newnum = $rs_stock['stock']-$rs["nowbuynum"];
			$this->fun->goods_stock_log($rs['id'],$detail['goods_id'],0,$cotnet,$goods_num,0,$oldnum,$newnum);    //库存日志
			//更新 db_goods_handstorage
			$post="";
			$detailimg= $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id='".$detail["goods_id"]."'");
			$post["goods_id"] = $detail['goods_id'];
			$post["goods_name"] = $detail['goods_name'];
			$post["oldnum"] = $oldnum;
			$post["newnum"] = $newnum;	//入库
			$post["images"] = $detailimg['thumb_url']?$detailimg['thumb_url']:"/fuman/images/s-l500.jpg";
			$post["goods_sku"] = $rs['sku'];
			$post["goods_instock"] = $rs["nowbuynum"];
			$post["istype"] = 5; //封箱出库
			$post["tostock"] =$storage_id;
			$post["status"] = 1;	//已处理状态
			$post["intime"] = time();
			$post["memo"] = $rs["groupid"];
			$post["oper"] = $_COOKIE["userid"];
			$post["opername"] =  $_COOKIE["username"];
			$post["storagename"] = $storage_name;
			$this->db->insert("db_goods_handstorage",$post);
			}

		}

		return;
	}

}

/* End of file Oversea_m.php */